<?php
namespace Api\Controller;

use Think\Image;

class AvatarController{

    const DEFAULT_AVATAR = "/Public/avatar/default.png";

    const LOCAL_PATH = "/Public/avatar/remote";

    protected $root_path = "";

    public function __construct()
    {  
        $this->root_path = realpath(__ROOT__) ?  realpath(__ROOT__) : realpath(APP_PATH."../" );

        $avatar = $this->root_path."/Public/avatar";
        if(!is_dir($avatar))
        {
            @mkdir($avatar);
        }
        if(!is_dir($avatar."/remote"))
        {
            @mkdir($avatar."/remote");
        }
        
    }

    public function index()
    {
        $id = I("uid");
        $gid = I("gid");

        if( empty($id) && empty($gid) )
        {
            return self::showImg($this->root_path.self::DEFAULT_AVATAR);
            throw new \Exception("Resource not found",404);
        }

        #获取用户头像
        if( !empty( $id ) )
        {
            $userPic = M("users")->where("user_id={$id}")->field('head_pic')->find();

            if( !$userPic || empty($userPic['head_pic']) )
            {
                $img = self::DEFAULT_AVATAR;
            }else{
                $img = $userPic['head_pic'];
            }

        }else{
            #获取群头像
            $img = M('im_group')->where([
                "groupid" => $gid
            ])->getField('avatar');

            if( !$img )
            {
                $img = self::DEFAULT_AVATAR;
            }
        }

        if( preg_match("/^https?:\/\/.*$/i",$img) )
        {
            $hash = $this->root_path.self::LOCAL_PATH."/".md5($img); 
            if( !is_file( $hash ) )
            {
                self::downloadImage($img,$hash);
            }
            $img = $hash;
        }else{
            $img = $this->root_path.$img;
            if( !is_file( $img ) ){
                $img = $this->root_path.self::DEFAULT_AVATAR;
            }
        }
        // var_dump($this->root_path);
        return self::showImg($img);
    }


    protected static function downloadImage($url, $filename )
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        // $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen( $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
    }

    protected static function showImg($img){
       
        try{
            $info = getimagesize($img);
            $imgExt = image_type_to_extension($info[2], false); //获取文件后缀
           
            $fun = "imagecreatefrom{$imgExt}";
            // var_dump($img,$info,$imgExt,\function_exists($fun));die;
            $imgInfo = $fun($img);         //1.由文件或 URL 创建一个新图象。如:imagecreatefrompng ( string $filename )
            $mime = $info['mime'];             
            // try{
            //     $mime = @image_type_to_mime_type(exif_imagetype($img)); //获取图片的 MIME 类型
            // }catch(\Exception $e)
            // {
            //     $mime = "image/jpeg";   
            // } 
            header('Content-Type:'.$mime);
            $quality = 90;
            if($imgExt == 'png') $quality = 9;   //输出质量,JPEG格式(0-100),PNG格式(0-9)
            $getImgInfo = "image{$imgExt}";
            $getImgInfo($imgInfo, null, $quality); //2.将图像输出到浏览器或文件。如: imagepng ( resource $image )
            imagedestroy($imgInfo);

        }catch(\Exception $e)
        {
            throw new \Exception("Resource not found",404);
        }
        
    }


}